import Http from '../../../../utils/http.js';
import { isEmpty } from '../../../../utils/util.js';
import { isvalidIDcard, isvalidPhone } from '../../../../utils/validate.js';
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    totalDay: 0,
    checkInDate: '2019-01-01',
    checkOutDate: '2019-01-02',
    startTime: '09:00',
    endTime:'09:00',
    idCert: '',
    name: '',
    userPhone: '',
    loading: false,
    room: [],
    subtotal: 0,//总计
    actualPayAmount: 0,//实际支付
    preferentialAmount: 0,//优惠金额
    discountAmount:0,//折扣
    submitWaiting: false,//订单提交中
    payWaiting: false,//支付中
    submitSucc: false,//订单提交成功
    orderState:'',
    disabled: false,//表单是否可编辑
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      ...(options),
      disabled: !isEmpty(options.orderState)
    })

    if (!isEmpty(this.data.orderCode)) {
      this.getOrderDetailByCode();
    } else {
      this.getOrderDetail()
    }
  },
  //根据订单编号查询订单详情
  getOrderDetailByCode() {
    this.setData({
      loading: true
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    Http.Request('GET', `/api/customer/order/getOrderDetailByOrderCode/${this.data.orderCode}/v1`).then(res => {
      const beginTime = res.beginTime.split(' ');
      const endTime = res.endTime.split(' ');
      this.setData({
        idCert: res.idCert,
        userPhone: res.userPhone,
        name: res.name,
        checkInDate: beginTime[0],
        checkOutDate: endTime[0],
        startTime: beginTime[1],
        endTime: endTime[1],
        actualPayAmount: res.actualPayAmount,
        discountAmount: res.discountAmount,
        subtotal: res.subtotal,
        preferentialAmount: res.preferentialAmount,
        remainingMills: res.remainingMills,
        totalDay: res.count,
        commodityName: res.commodity[0].commodityName,
        commoditySellingPoint: res.commodity[0].commoditySellingPoint,
        commodityCode: res.commodity[0].commodityCode,
        commodityImage: res.commodity[0].firstImage,
        labels: res.commodity[0].product,
        bizid: res.commodity[0].productCode,
        orderState: res.orderState.name,
        disabled: !isEmpty(res.orderState.name),
        loading: false,
        submitSucc: true
      })
      wx.hideLoading();
      const data = {
        "beginDate": `${this.data.checkInDate} ${this.data.startTime}`,
        "endDate": `${this.data.checkOutDate} ${this.data.endTime}`,
        "commodity": [
          {
            "commodityCode": this.data.commodityCode,
            "count": 1,
            "productBizid": this.data.bizid || ''
          }
        ]
      };
      Http.Request('POST', `/api/customer/order/orderMoneyDetail/v1`, data).then(res => {
        this.setData({
          car:res.car
        })
      }).catch(err => {
        this.setData({
          isShowDetail: false
        })
      })
    })
  },
  bindKeyInput(e) {
    const value = e.detail.value;
    const key = e.target.dataset.key;
    this.setData({
      [key]: value
    })
  },

  //显示弹窗
  showModal() {
    this.selectComponent("#maskModals").showChoose()
  },
  //获取订单明细
  getOrderDetail() {
    this.setData({
      loading: true
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const data = {
      "beginDate": `${this.data.checkInDate} ${this.data.startTime}`,
      "endDate": `${this.data.checkOutDate} ${this.data.endTime}`,
      "commodity": [
        {
          "commodityCode": this.data.commodityCode,
          "count": 1,
          "productBizid": this.data.bizid||''
        }
      ]
    };
    Http.Request('POST', `/api/customer/order/orderMoneyDetail/v1`, data).then(res => {
      this.setData({
        loading: false,
        ...(res)
      })
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      app.globalFn.reLoad(this.getOrderDetail, err)
    })
  },
  //提交订单
  submitOrder() {
    if (this.data.submitWaiting || this.data.payWaiting) return
    if (this.data.submitSucc) {
      this.handlePay();
      return
    }
    //数据校验
    if (isEmpty(this.data.name)) {
      wx.showToast({
        title: '请填写入住人姓名',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    if (isEmpty(this.data.userPhone)) {
      wx.showToast({
        title: '请填写手机号码',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    if (isEmpty(this.data.idCert)) {
      wx.showToast({
        title: '请填写身份证号码',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    if (!isvalidPhone(this.data.userPhone)) {
      wx.showToast({
        title: '请填写正确的手机号码',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    if (!isvalidIDcard(this.data.idCert)) {
      wx.showToast({
        title: '请填写正确的身份证号码',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    this.setData({
      submitWaiting: true
    })
    wx.showLoading({
      title: '订单提交中',
      mask: true
    })
    const data = {
      beginDate: `${this.data.checkInDate} ${this.data.startTime}`,
      commodity: [{
        commodityCode: this.data.commodityCode,
        count: 1,//租车商品同时段最多一个
        productBizid: this.data.bizid
      }],
      endDate: `${this.data.checkOutDate} ${this.data.endTime}`,
      idCert: this.data.idCert,
      name: this.data.name,
      personNumber: this.data.personNumber,
      userPhone: this.data.userPhone,
    }
    Http.Request('POST', `/api/customer/order/placeOrder/CAR_COMMODITY/v1`, data).then(res => {
      wx.showToast({
        title: '订单提交成功',
        icon: "success",
        duration: app.globalData.duration
      })
      wx.hideLoading();
      this.setData({
        orderCode: res.orderCode,
        remainingMills: res.mills,
        orderState: res.orderState.name,
        submitWaiting: false,
        submitSucc: true
      })
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err,
        icon: "none",
        duration: app.globalData.duration
      })
      this.setData({
        submitWaiting: false,
        submitSucc: false
      })
    })

  },
  //支付
  handlePay() {
    this.setData({
      payWaiting: true
    })
    Http.Request('POST', `/api/customer/audio/pay/${this.data.orderCode}/v1`).then(res => {
      wx.requestPayment({
        'timeStamp': res.timeStamp,
        'nonceStr': res.nonceStr,
        'package': res.package,
        'signType': res.signType,
        'paySign': res.sign,
        'success': (res) => {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: app.globalData.duration
          })
          this.setData({
            orderState: 'PAID'
          })
        },
        complete: () => {
          this.setData({
            payWaiting: false
          })
        }
      })
    }).catch(err => {
      this.setData({
        payWaiting: false
      })
      wx.showToast({
        title: err,
        icon: 'none',
        duration: app.globalData.duration
      })
    })
  }
})